package com.zzyl.serve.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.uuid.UUID;
import com.zzyl.serve.dto.DeviceDto;
import com.zzyl.serve.vo.DeviceDetailVo;
import com.zzyl.serve.vo.DeviceReportDataVo;
import com.zzyl.serve.vo.ProductVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.serve.mapper.DeviceMapper;
import com.zzyl.serve.domain.Device;
import com.zzyl.serve.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备Service业务层处理
 * 
 * @author chenyang
 * @date 2025-08-22
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private IoTDAClient client;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询设备
     * 
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备列表
     * 
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return deviceMapper.insert(device);
    }

    /**
     * 修改设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return deviceMapper.updateById(device);
    }

    /**
     * 批量删除设备
     * 
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备信息
     * 
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return deviceMapper.deleteById(id);
    }

    @Override
    public void syncProductionList() {
        //1.向华为云平台发请求，查询产品列表
        ListProductsRequest request = new ListProductsRequest();
        //发请求拿到回应（产品概要信息）
        ListProductsResponse response = client.listProducts(request);
        //拿到产品列表
        List<ProductSummary> products = response.getProducts();


        if (response.getHttpStatusCode() != 200){
            throw new RuntimeException("物联网接口-同步产品失败");
        }

        //2.将产品列表缓存到Redis里
        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCTION_LIST_KEY, JSONUtil.toJsonStr(products));


    }

    @Override
    public List<ProductVo> getAllProduct() {
        //1.从缓存里面获取数据
        String jsonStr = (String) redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCTION_LIST_KEY);

        if (jsonStr ==null || "".equals(jsonStr)){
            return Collections.emptyList();
        }

        //将JSON字符串转成集合
        List<ProductVo> list = JSONUtil.toList(jsonStr, ProductVo.class);

        return list;
    }

    @Override
    public void register(DeviceDto dto) {
        //1.先进行校验
        //如果设备已经存在于数据库中了：抛异常
        LambdaQueryWrapper<Device> wrapper = Wrappers.<Device>lambdaQuery()
                .eq(Device::getNodeId, dto.getNodeId());
        Device device = deviceMapper.selectOne(wrapper);
        if (device!=null){
            throw new BaseException("设备标识码已存在");
        }
        //如果设备名称已经存在于数据库中，抛异常
        wrapper = Wrappers.<Device>lambdaQuery()
                .eq(Device::getDeviceName, dto.getDeviceName());
         device = deviceMapper.selectOne(wrapper);
        if (device!=null){
            throw new BaseException("设备名称已存在");
        }

        //如果设备同一位置绑定了同一类型的产品：抛异常
        Wrappers.<Device>lambdaQuery()
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getPhysicalLocationType, dto.getPhysicalLocationType())
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getProductKey, dto.getProductKey());
        if (device!=null){
            throw new BaseException("该位置或老人已经绑定该设备");
        }



        //2.将该设备信息注册到华为云
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.setProductId(dto.getProductKey());
        body.setDeviceName(dto.getDeviceName());
        body.setNodeId(dto.getNodeId());

        AuthInfo authInfo = new AuthInfo();
        String secret = UUID.randomUUID().toString(true);
        authInfo.setSecret(secret);
        body.setAuthInfo(authInfo);

        request.withBody(body);


        AddDeviceResponse response = client.addDevice(request);

        String iotId = response.getDeviceId();

        //3.保存到数据库
        device =new Device();
        BeanUtils.copyProperties(dto,device,Device.class);
        device.setIotId(iotId);
        device.setSecret(secret);


        save(device);
    }

    @Override
    public DeviceDetailVo getInfo(String iotId) {

        //先从数据库的device表里查询设备信息
        LambdaQueryWrapper<Device> wrapper = Wrappers.<Device>lambdaQuery()
                .eq(Device::getIotId, iotId);
        Device one = getOne(wrapper);
        if (one ==null) {
            return null;
        }
        //再调用华为云的API，得到设备的状态与激活时间
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);

        if (response.getHttpStatusCode()!=200) {
            throw new BaseException("物联网接口 -查询设备信息接口失败");
        }

        //再将结果封装成vo对象
        DeviceDetailVo vo = new DeviceDetailVo();
        BeanUtils.copyProperties(one,vo);
        vo.setBindingLocation(Long.parseLong(one.getBindingLocation()));
        vo.setCreateTime(one.getCreateTime().toInstant().atZone(ZoneId.of("Asia/Shanghai")).toLocalDateTime());
        vo.setDeviceStatus(response.getStatus());

        String activeTimeStr = response.getActiveTime();
        if (StringUtils.isNotEmpty(activeTimeStr)){
            LocalDateTime dateTime = LocalDateTime.parse(activeTimeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"));
            //将零时区的dateTime转换成东八区的localdatetime对象
            vo.setActiveTime(dateTime.atZone(ZoneId.of("UTC")).withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime());


        }

        return vo;
    }

    @Override
    public List<DeviceReportDataVo> queryServiceProperties(String iotId) {
        //向华为云平台发请求，查询设备影子信息
        ShowDeviceShadowRequest request =new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);

        ShowDeviceShadowResponse response = client.showDeviceShadow(request);

        List<DeviceShadowData> shadow = response.getShadow();
        if (shadow == null || shadow.isEmpty()){
            return Collections.emptyList();
        }

        System.out.println("shadow = " + shadow);
        //获取设备上报的数据
        Map<String,Object> properties = (Map<String,Object>)shadow.get(0).getReported().getProperties();
        String time = shadow.get(0).getReported().getEventTime();//上报时间
        LocalDateTime reportTime = LocalDateTime.parse(time, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'"));
        LocalDateTime eventTime = reportTime.atZone(ZoneId.of("UTC")).withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();


        //封装结果
        ArrayList<DeviceReportDataVo> list = new ArrayList<>();
        //循环properties里面的所有数据封装到vo里面
        for (Map.Entry<String, Object> entry : properties.entrySet()) {
            DeviceReportDataVo vo = new DeviceReportDataVo();
            vo.setFunctionId(entry.getKey());
            vo.setEventTime(eventTime);
            vo.setValue(entry.getValue());
            list.add(vo);
        }
        return list;
    }

    @Override
    public void modifyDevice(DeviceDto dto) {
        //更新华为云平台信息
        UpdateDeviceRequest request =new UpdateDeviceRequest();
        request.setDeviceId(dto.iotId);
        UpdateDevice body = new UpdateDevice();
        body.setDeviceName(dto.getDeviceName());
        body.setDescription(dto.getDeviceDescription());

        request.setBody(body);

        UpdateDeviceResponse response = client.updateDevice(request);


        //更新数据库表信息
        Device device = new Device();
        device.setIotId(dto.iotId);
        device.setDeviceName(dto.getDeviceName());
        device.setDeviceDescription(dto.getDeviceDescription());
        device.setUpdateTime(new Date());
        device.setBindingLocation(dto.getBindingLocation());
        device.setLocationType(dto.getLocationType());
        device.setPhysicalLocationType(dto.getPhysicalLocationType());
        device.setNodeId(dto.getNodeId());
        device.setRemark(dto.getRemark());
        device.setProductName(dto.getProductName());
        device.setProductKey(dto.getProductKey());
        device.setId(dto.getId());

        //将device里面的信息更新到数据库device表中，
        updateById(device);




    }

    @Override
    public void deleteDeviceByiotId(String iotId) {
        //根据IoTID去华为云删除设备

        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceId(iotId);

        DeleteDeviceResponse response = client.deleteDevice(request);


        //在数据库表里删除设备,根据iotid删
        LambdaQueryWrapper<Device> wrapper = Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId);
        deviceMapper.delete(wrapper);



    }
}
